package com.ruoyi.web.controller.jjm;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/jjm/manager")
public class ManagerController extends BaseController {

    public static final long COUNTY_ROLE = 100;
    public static final long TOWN_ROLE = 101;
    public static final long VILLAGE_ROLE = 102;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private SysPasswordService passwordService;

    private String prefix = "jjm/manager";

    @GetMapping()
    public String user(ModelMap mmap)
    {
        createUserLevel(mmap,"list");
        return prefix + "/list";
    }

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysUser user)
    {
        SysUser sysUser = ShiroUtils.getSysUser();
        user.setParentId(sysUser.getDeptId());
        startPage();
        List<SysUser> list = userService.selectByDeptParentId(sysUser.getDeptId());
        return getDataTable(list);
    }


    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        SysUser user = ShiroUtils.getSysUser();
        SysDept filter = new SysDept();
        createUserLevel(mmap,"add");
        List<SysDept> deptList = deptService.selectDeptByParentId(user.getDeptId());
        mmap.put("deptList",deptList);
        return prefix + "/add";
    }

    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id")Long id, ModelMap mmap)
    {
        SysUser user = userService.selectUserById(id);
//        SysUser sysUser = ShiroUtils.getSysUser();
        createUserLevel(mmap,"edit");
        List<SysDept> deptList = deptService.selectDeptByParentId(user.getDept().getParentId());
        mmap.put("deptList",deptList);
        mmap.put("user",user);

        return prefix + "/edit";
    }


    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysUser user)
    {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName())))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        SysUser sysUser = ShiroUtils.getSysUser();
        SysDept dept = sysUser.getDept();
        String[] ancestors = dept.getAncestors().split(",");
        int level = ancestors.length;
        if(level == 1){
            user.setRoleId(COUNTY_ROLE);
            user.setRoleIds(new Long[]{COUNTY_ROLE});
        }else if(level == 2){
            user.setRoleId(TOWN_ROLE);
            user.setRoleIds(new Long[]{TOWN_ROLE});
        }else if(level == 3){
            user.setRoleId(VILLAGE_ROLE);
            user.setRoleIds(new Long[]{VILLAGE_ROLE});
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getOriginalPwd(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改保存用户
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysUser user)
    {
        userService.checkUserAllowed(user);
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        SysUser oldUser = userService.selectUserById(user.getUserId());
        if(CollectionUtils.isNotEmpty(oldUser.getRoles())){
            Long[] roleIds = new Long[]{oldUser.getRoles().get(0).getRoleId()};
            user.setRoleIds(roleIds);
        }
        user.setDeptId(user.getDeptId());
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getOriginalPwd(), user.getSalt()));
        user.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(userService.updateUser(user));
    }

    private void createUserLevel(ModelMap mmap,String page){
        SysUser user = ShiroUtils.getSysUser();
        SysDept dept = user.getDept();
        String[] ancestors = dept.getAncestors().split(",");
        int level = ancestors.length;
        String levelTitle = "";
        switch (level){
            case 1:
                if(page.equals("list")){
                    levelTitle = "县（市）/区";
                }else{
                    levelTitle = "县";
                }
                break;
            case 2:
                levelTitle = "乡镇";
                break;
            case 3:
                levelTitle = "村";
                break;
        }
//        if(user.isAdmin()){
//            level = 0;
//            levelTitle = "市";
//        }
        mmap.put("level",level);
        mmap.put("levelTitle",levelTitle);
        mmap.put("sysUser",user);
    }
}
